﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Parser;
namespace SqlFormatter
{
    public class SqlFormatter
    {
        public SqlFormatter(string sql)
        {
            SqlParser parser = new SqlParser();
            parser.Parse(sql);

            fields = splitString(parser.FieldsClause);
            froms = splitString(parser.FromClause);
            wheres = splitString(parser.WhereClause);
        }

        List<string> fields = new List<string>();
        List<string> froms = new List<string>();
        List<string> wheres = new List<string>();
        const string indent = "\t";

        public override string ToString()
        {
            string sql = string.Empty;

            sql += string.Format("SELECT ");
            sql += "\n";
            sql += FormatList(fields);

            sql += string.Format("FROM ");
            sql += "\n";
            sql += FormatList(froms);

            sql += string.Format("WHERE ");
            sql += "\n";
            sql += FormatList(wheres);

            return sql;
        }

        string FormatList(List<string> lst)
        {
            string result = string.Empty;

            bool bFirst = true;
            foreach (string s in lst)
            {
                result += indent;
                if (bFirst)
                {
                    bFirst = false;

                    result += " ";
                }
                else
                {
                    result += ",";
                }

                result += s;
                result += " \n";
            }
            return result;
        }

        List<string> splitString(string s)
        {
            string[] tokens = s.Split(',');

            List<string> lst = new List<string>();
            foreach (string token in tokens)
            {
                lst.Add(token.Trim());
            }
            return lst;
        }
    }
}
